package com.whfc.ms.api.emp.controller;

import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.emp.dto.*;
import com.whfc.emp.param.*;
import com.whfc.emp.service.AppEmpWarnService;
import com.whfc.entity.dto.msg.AppWarnMsgRecDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.api.emp.service.MsAppEmpWarnService;
import com.whfc.emp.service.AppWorkPlanService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author sun_guodong
 * @description 人员报警设置
 * @date 2020-05-29
 */
@RequiresPermissions("emp/warn")
@RestController
@RequestMapping("/ms/api/warn/emp")
public class AppEmpWarnController {
    private static final Logger logger = LoggerFactory.getLogger(AppEmpWarnController.class);

    @Autowired
    private MsAppEmpWarnService msAppEmpWarnService;

    @GetMapping("/setting/list")
    public Result settingList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                              @RequestParam("deptId") Integer deptId,
                              @RequestParam("pageNum") Integer pageNum,
                              @RequestParam("pageSize") Integer pageSize,
                              @RequestParam(value = "keyword", required = false) String keyword,
                              @RequestParam(value = "ruleType", required = false) Integer ruleType,
                              @RequestParam(value = "enableFlag", required = false) Integer enableFlag,
                              @RequestParam(value = "warnType", required = false) Integer warnType) {
        logger.info("人员报警规则列表,loginer:{},deptId:{},pageNum:{},pageSize:{},keyword:{},ruleType:{},enableFlag:{},warnType:{}",
                user.getUsername(), deptId, pageNum, pageSize, keyword, ruleType, enableFlag, warnType);
        PageData<AppWarnRuleDTO> pageData = msAppEmpWarnService.settingList(deptId, pageNum, pageSize, keyword, ruleType, enableFlag, warnType);
        return ResultUtil.success(pageData);
    }

    @RequiresPermissions("emp/warnSetting/time")
    @PostMapping("/setTime")
    public Result setTime(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @Validated @RequestBody AppWarnSetTimeParam request) {
        logger.info("人员报警设置报警时间,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpWarnService.setTime(request);
        return ResultUtil.success();
    }


    @GetMapping("/user/list")
    public Result userList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                           @RequestParam("ruleId") Integer ruleId) {
        logger.info("人员报警信息接收人及接收方式,loginer:{},ruleId:{}", user.getUsername(), ruleId);
        AppWarnMsgRecDTO warnMsgRecDTO = msAppEmpWarnService.userList(ruleId);
        return ResultUtil.success(warnMsgRecDTO);
    }

    @RequiresPermissions("emp/warnSetting/recept")
    @PostMapping("/setUser")
    public Result setUser(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @Validated @RequestBody AppWarnEmpSetUserParam request) {
        logger.info("人员报警设置报警接收人,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpWarnService.setUser(request);
        return ResultUtil.success();
    }


    @GetMapping("/record/list")
    public Result recordList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("deptId") Integer deptId,
                             @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize,
                             @RequestParam(value = "state", required = false) Integer state,
                             @RequestParam(value = "ruleType", required = false) Integer ruleType,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "startDate", required = false) Date startDate,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "endDate", required = false) Date endDate) {
        logger.info("人员报警记录列表,loginer:{},deptId:{},pageNum:{},pageSize:{},state:{},ruleType:{},startDate:{},endDate:{}",
                user.getUsername(), deptId, pageNum, pageSize, state, ruleType, startDate, endDate);
        Date startTime = null;
        Date endTime = null;
        if (startDate != null) {
            startTime = DateUtil.getDateBegin(startDate);
        }
        if (endDate != null) {
            endTime = DateUtil.getDateEnd(endDate);
        }
        PageData<AppWarnEmpRecordDTO> pageData = msAppEmpWarnService.recordList(deptId, pageNum, pageSize, state, ruleType, startTime, endTime);
        return ResultUtil.success(pageData);
    }

    @GetMapping("/record/num")
    public Result num(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @RequestParam("deptId") Integer deptId,
                      @RequestParam(value = "state", required = false) Integer state,
                      @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "startDate", required = false) Date startDate,
                      @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "endDate", required = false) Date endDate) {
        logger.info("人员报警数量,loginer:{},pageSize:{},state:{},startDate:{},endDate:{}",
                user.getUsername(), deptId, state, startDate, endDate);
        Date startTime = null;
        Date endTime = null;
        if (startDate != null) {
            startTime = DateUtil.getDateBegin(startDate);
        }
        if (endDate != null) {
            endTime = DateUtil.getDateEnd(endDate);
        }
        AppWarnEmpRecordNumDTO data = msAppEmpWarnService.num(deptId, state, startTime, endTime);
        return ResultUtil.success(data);
    }


    @GetMapping("/record/detail")
    public Result recordDetail(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestParam("warnId") Integer warnId) {
        logger.info("人员报警详情,loginer:{},warnId:{}", user.getUsername(), warnId);
        AppWarnEmpRecordDetailDTO data = msAppEmpWarnService.recordDetail(warnId);
        return ResultUtil.success(data);
    }

    @RequiresPermissions("emp/warnRecord/dealSingle")
    @PostMapping("/record/handle")
    public Result handle(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                         @Validated @RequestBody AppWarnHandleParam request) {
        logger.info("处理人员报警,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpWarnService.handle(user, request);
        return ResultUtil.success();
    }

    @RequiresPermissions("emp/warnRecord/deal")
    @PostMapping("/record/batchHandle")
    public Result batchHandle(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                              @Validated @RequestBody WarnBatchHandleParam param) {
        logger.info("批量处理人员报警,loginer:{},param:{}", user.getUsername(), param.toString());
        param.setUserId(user.getId());
        param.setUserName(user.getNickname());
        param.setPhone(user.getPhone());
        msAppEmpWarnService.batchHandle(param);
        return ResultUtil.success();
    }

    @PostMapping("/record/del")
    public Result del(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @Validated @RequestBody WarnBatchDelParam param) {
        logger.info("批量删除人员报警记录,loginer:{},param:{}", user.getUsername(), param.toString());
        msAppEmpWarnService.del(param);
        return ResultUtil.success();
    }

    @RequiresPermissions("emp/warnSetting/sysForbidden")
    @PostMapping("/setting/enable")
    public Result enable(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                         @Validated @RequestBody AppEmpWarnEnableParam request) {
        logger.info("启用/禁用人员报警规则,loginer:{},param:{}", user.getUsername(), request.toString());
        msAppEmpWarnService.enable(request);
        return ResultUtil.success();
    }


    /**************************************系统报警********************************************/
    @PostMapping("/setting/add")
    public Result settingAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @Validated @RequestBody AppEmpWarnAddParam param) {
        logger.info("添加人员报警规则,loginer:{},param:{}", user.getUsername(), param.toString());
        msAppEmpWarnService.settingAdd(param);
        return ResultUtil.success();
    }

    @PostMapping("/setting/edit")
    public Result settingEdit(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                              @Validated @RequestBody AppEmpWarnEditParam param) {
        logger.info("编辑人员报警规则,loginer:{},param:{}", user.getUsername(), param.toString());
        msAppEmpWarnService.settingEdit(param);
        return ResultUtil.success();
    }

    @PostMapping("/setting/del/{ruleId}")
    public Result settingDel(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @PathVariable("ruleId") Integer ruleId) {
        logger.info("删除人员报警规则,loginer:{},ruleId:{}", user.getUsername(), ruleId);
        msAppEmpWarnService.settingDel(ruleId);
        return ResultUtil.success();
    }

    @GetMapping("/object/list")
    public Result objectList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("ruleId") Integer ruleId,
                             @RequestParam(value = "empName", required = false) String empName) {
        logger.info("查询已有的报警人员,loginer:{},ruleId:{},empName:{}", user.getUsername(), ruleId, empName);
        ListData<AppEmpDTO> listData = msAppEmpWarnService.objectList(ruleId, empName);
        return ResultUtil.success(listData);
    }

    @GetMapping("/getAllObject")
    public Result getAllObject(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestParam("ruleId") Integer ruleId,
                               @RequestParam(value = "empName", required = false) String empName) {
        logger.info("查询可供选择的报警人员,loginer:{},ruleId:{},empName:{}", user.getUsername(), ruleId, empName);
        ListData<AppEmpDTO> listData = msAppEmpWarnService.getAllObject(ruleId, empName);
        return ResultUtil.success(listData);
    }

    @RequiresPermissions("emp/warnSetting/sysemp")
    @PostMapping("/object/add")
    public Result objectAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                            @Validated @RequestBody EmpWarnObjectAddParam param) {
        logger.info("添加报警人员,loginer:{},param:{}", user.getUsername(), param.toString());
        msAppEmpWarnService.objectAdd(param);
        return ResultUtil.success();
    }

    /**
     * 手动触发工作计划报警消息发送给监护人
     * @param user 当前登录用户
     * @return 处理结果
     */
    @RequiresPermissions("emp/warnRecord/deal")
    @PostMapping("/workplan/sendAlarmToGuardians")
    public Result sendAlarmMessageToWorkPlanGuardians(@SessionAttribute(SessionAttr.MS_USER) SysUser user) {
        logger.info("手动触发工作计划报警消息发送给监护人,loginer:{}", user.getUsername());

        try {
            boolean result = msAppEmpWarnService.sendAlarmMessageToWorkPlanGuardians();
            
            if (result) {
                logger.info("工作计划报警消息发送成功,loginer:{}", user.getUsername());
                return ResultUtil.success("工作计划报警消息发送成功");
            } else {
                logger.warn("工作计划报警消息发送未处理任何记录,loginer:{}", user.getUsername());
                return ResultUtil.success("未找到需要处理的工作计划报警记录");
            }
            
        } catch (Exception e) {
            logger.error("工作计划报警消息发送失败,loginer:{}", user.getUsername(), e);
            return ResultUtil.failure("工作计划报警消息发送失败: " + e.getMessage());
        }
    }

}